package com.xatu.yl.storeshopping.activity.RegisterAndLogin;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.namespace.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xatu.yl.storeshopping.AppContent;
import com.xatu.yl.storeshopping.util.ToastUtil;
import com.xatu.yl.storeshopping.util.UuidUtil;
import com.xatu.yl.storeshopping.vo.Register.LoginInfo;
import com.xatu.yl.storeshopping.vo.Register.UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;


public class UserRegisterActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private RadioGroup sex_group;
    private EditText userId,nickName,pwd,confirmPwd,address,phone;
    private String sex = "";
    private Button reg_btn,uploadImgBtn;
    private LinearLayout catch_photo;
    private static final int REQUEST_CODE_TAKE_PICTURE = 0;
    private Uri mUri;
    private File mFile;
    /**
     * 创建出唯一的一个标识，用来标识文件，同时也避免多次选择/拍摄照片，导致存在多余的照片
     */
    private String uuid = UuidUtil.generateUuid();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);

        //设置拍摄的照片的存储路径
        mFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/icon/"+ uuid +"_user_"+".jpg");
        String str = "com.xatu.yl.storeshopping.fileprovider";
        mUri = FileProvider.getUriForFile(this, str, mFile);
        if (!mFile.getParentFile().exists()) {
            mFile.getParentFile().mkdirs();
        }

        //选择性别
        sex_group = findViewById(R.id.sex_group);
        sex_group.setOnCheckedChangeListener(this);
        //用户账号
        userId = findViewById(R.id.userId);
        //昵称
        nickName = findViewById(R.id.nickName);
        //密码
        pwd = findViewById(R.id.pwd);
        //确认密码
        confirmPwd = findViewById(R.id.confirmPwd);
        //收货地址
        address = findViewById(R.id.address);
        //联系方式
        phone = findViewById(R.id.phone);

        //注册按钮
        reg_btn = findViewById(R.id.reg_btn);
        reg_btn.setOnClickListener(this);
        //选择头像
        catch_photo = findViewById(R.id.catch_photo);
        catch_photo.setOnClickListener(this);

        uploadImgBtn = findViewById(R.id.uploadImgBtn);
        uploadImgBtn.setOnClickListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == R.id.user_radiobtn){
            sex = "user";
        }
        if(checkedId == R.id.shopper_radiobtn){
            sex = "shopper";
        }
    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.reg_btn){
            if (!pwd.getText().toString().equals(confirmPwd.getText().toString())){
                new ToastUtil(getApplicationContext()).showToast("请确保密码相同",R.drawable.warning,R.color.warning, Toast.LENGTH_SHORT);
            }else{
                try {
                    register();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        if(v.getId()==R.id.catch_photo){
            //更换/选择头像
            //弹出模态框
            BottomSheetDialog dialog = new BottomSheetDialog(getApplicationContext());
            // 设置底部弹出框的布局文件
            dialog.setContentView(R.layout.bottom_dialog);
            dialog.show();
            //获取功能按钮
            LinearLayout camera_btn = dialog.findViewById(R.id.camera_btn);
            LinearLayout photo_btn = dialog.findViewById(R.id.photo_btn);
            LinearLayout cancel_btn = dialog.findViewById(R.id.cancel_btn);
            //设置监听事件
            camera_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //拍照
                    showTakePhotoActivity();
                }
            });
            photo_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转去图库
                }
            });
            cancel_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

        }
        if(v.getId()==R.id.uploadImgBtn){
            //上传图片
            uploadUserIcon();
        }
    }

    /**
     * 注册
     */
    private void register() throws JSONException{
        AsyncHttpClient client = new AsyncHttpClient();
        JSONObject params = new JSONObject();
        params.put("loginInfo",new LoginInfo(userId.getText().toString(),pwd.getText().toString(),sex));
        /**
         * 这里的第五个参数是图片的地址，思路如下：
         * 1.在提交注册信息的时候，先将图片进行上传，然后获取到一个返回的地址，这个地址就代表图片在服务器中的地址
         * 2.将地址与其他参数，作为注册信息进行第二次上传，这次是注册信息上传
         */
        params.put("userInfo",new UserInfo(nickName.getText().toString(),
                sex,
                address.getText().toString(),
                phone.getText().toString(),
                AppContent.uploadUrl));
    }


    private void showTakePhotoActivity() {
        // TODO: 检查权限是否足够
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            // TODO: 需要考虑如果系统没有匹配的intent情况
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra("android.intent.extras.CAMERA_FACING", 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
            startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_TAKE_PICTURE:
                if (resultCode == -1) {
                    new Thread() {
                        @Override
                        public void run() {
                            //将拍到的照片压缩后保存到本地，并根据路径将其转成字节数组
                            Bitmap bitmap = compressBySize(mFile.getAbsolutePath(), 480, 800);  //设置压缩后图片的高度和宽度
                            try {
                                saveFile(bitmap, mFile.getAbsolutePath());
                            } catch (IOException e) {

                            }
                        }
                    }.start();
                }
        }
        finish();
    }


    /**
     * 上传用户图标
     */
    private void uploadUserIcon() {

        File file = new File(mFile.getAbsolutePath());
        RequestParams params = new RequestParams();
        try {
            params.put("file", file);
        } catch(FileNotFoundException e) {

        }
        AsyncHttpClient client = new AsyncHttpClient();

        client.post(AppContent.baseUrl,params,uploadImgHandler);
    }


    /**
     * 图片上传回调
     */
    public JsonHttpResponseHandler uploadImgHandler=new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(int statusCode, org.apache.http.Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            try {
                //{"status":200,"result":{"upload\/ugp\/amos_studio\/BC3DF58F9BFF7B63059C668E950A790.jpg":"d78baad2-8fd5-4b14-861a-5433bba71b42_face_e.jpg"},"traceId":"1589814332890312705","devMessage":"SUCCESS","message":"","path":"\/v1\/filestorage"}
                if (response.getInt("status")!=200){
                    new ToastUtil(getApplicationContext()).showToast("图片上传失败",R.drawable.error,R.color.error,Toast.LENGTH_SHORT);
                }else {
                    AppContent.isUploadUserImgSuccess = true;
                    new ToastUtil(getApplicationContext()).showToast("图片上传成功",R.drawable.success,R.color.success,Toast.LENGTH_SHORT);
                    String result = response.getString("result");
                    JSONObject resultJson = new JSONObject(result);
                    Iterator<String> keys = resultJson.keys();
                    while (keys.hasNext()){
                        AppContent.uploadUrl=keys.next();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, org.apache.http.Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            new ToastUtil(getApplicationContext()).showToast("图片上传消息返回失败",R.drawable.error,R.color.error,Toast.LENGTH_SHORT);
        }
    };


    /**
     * 压缩图片尺寸，减小图片大小
     * @param pathName
     * @param targetWidth
     * @param targetHeight
     * @return
     */
    private static Bitmap compressBySize(String pathName, int targetWidth,
                                         int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }

    /**
     * 保存压缩后的图片
     * @param bitmap
     * @param filePath2
     * @throws IOException
     */
    private void saveFile(Bitmap bitmap, String filePath2) throws IOException {
        // 创建一个文件对象
        File testFile = new File(filePath2);
        if (testFile.exists()) {
            //如果文件存在，则删除
            testFile.delete();
        }

        File myCaptureFile = new File(filePath2);
        /**
         * 缓冲输出流
         */
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
        bos.flush();
        bos.close();
    }
}